﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BYS.XiAnComDept.BussLogic;
using System.Data.Entity;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading;
using EntityFramework.Extensions;
using FirstFloor.ModernUI.Windows;

namespace BYS.XiAnComDept.App.Pages
{
    /// <summary>
    /// Interaction logic for FundEdit.xaml
    /// </summary>
    public partial class FundEdit : UserControl, IContent
    {
        BllFactory bllFactory = new BllFactory();
        List<ProjectField> availableProjectFieldNames = null;
        public List<Company> AllCompanies = null;
        public List<FundType> AllFundTypes = null;

        public AddOrEdit FormStatus = AddOrEdit.Add;

        public FundEdit()
        {
            InitializeComponent();
            this.InitUI();
        }

        public void InitUI()
        {

            this.AllCompanies = bllFactory.CompanyBll.GetCompanies();
            this.AllFundTypes = bllFactory.FundTypeBll.GetAllFundTypes();

            this.ComboBoxCom.DisplayMemberPath = "CompanyName";
            this.ComboBoxCom.ItemsSource = this.AllCompanies;

            this.ComboBoxYear.ItemsSource = UIHelper.GetAllYears();
            this.ComboBoxFundType.ItemsSource = this.AllFundTypes;
            this.ComboBoxFundType.DisplayMemberPath = "FundTypeName";
            this.ComboBoxStatus.ItemsSource = UIHelper.GetAllFundStatus();
        }

        public Fund Fund { get; set; }

        #region Nagivation
        public void OnFragmentNavigation(FirstFloor.ModernUI.Windows.Navigation.FragmentNavigationEventArgs e)
        {
        }

        public void OnNavigatedFrom(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
        }

        public void OnNavigatedTo(FirstFloor.ModernUI.Windows.Navigation.NavigationEventArgs e)
        {
            Dictionary<string, string> pars = e.Source.GetQuery();
            if (pars.Keys.Contains("FundGuid"))
            {
                Guid fundGuid = Guid.Parse(pars["FundGuid"]);
                this.Fund = bllFactory.Db.Funds
                          .Include(x => x.Company)
                          .Include(x => x.FundType)
                          .Include(x => x.ProjectFields)
                          .SingleOrDefault(x => x.FundGuid == fundGuid);
                if (this.Fund != null)
                {
                    this.Fund.Company = this.AllCompanies.Single(x => x.ComGuid == this.Fund.Company.ComGuid);
                    this.Fund.FundType = this.AllFundTypes.Single(x => x.FundTypeGuid == this.Fund.FundType.FundTypeGuid);
                    this.Fund.ProjectFields.CollectionChanged += ProjectFields_CollectionChanged;
                    this.FormStatus = AddOrEdit.Edit;
                    this.SetDataContext( this.Fund);
                    this.ComboBoxCom.IsEnabled = false;
                    this.ComboBoxYear.IsEnabled = false;
                    this.ComboBoxFundType.IsEnabled = false;
                    return;
                }
                else
                {
                    MessageBox.Show("资金数据不存在，请重新查询！", "错误");
                    NavigationCommands.GoToPage.Execute("/Pages/FundQuery.xaml", this);
                }
            }
            else
            {
                this.Fund = new Fund();
                this.Fund.ProjectFields = new ObservableCollection<ProjectField>();
                this.Fund.ProjectFields.CollectionChanged += ProjectFields_CollectionChanged;
                this.DataContext = this.Fund;
                this.ButtonDelete.IsEnabled = false;
            }
        }

        public void OnNavigatingFrom(FirstFloor.ModernUI.Windows.Navigation.NavigatingCancelEventArgs e)
        {
        }

        #endregion

        private void ProjectFields_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if(this.availableProjectFieldNames !=null)
            {
                this.BindAvailableProjectFieldName(this.availableProjectFieldNames);
            }
        }

        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            ValidateForm validator = new ValidateForm();
            if (this.ShowError(validator.ValidControls(this.GridForm))) { return; }
            switch (this.FormStatus)
            {
                case AddOrEdit.Add:
                    bllFactory.Db.Funds.Add(this.Fund);
                    if(this.Fund.ProjectFields.Count>0)
                    {
                        bllFactory.Db.ProjectFields.AddRange(this.Fund.ProjectFields);
                    }
                    bllFactory.Db.SaveChanges();
                    MessageBox.Show("专项资金信息添加成功！\n你可以继续修改它的信息。", "专项资金信息添加成功");
                    NavigationCommands.GoToPage.Execute(
                        "/Pages/FundEdit.xaml?FundGuid=" +this.Fund.FundGuid,
                        this);
                    break;
                case AddOrEdit.Edit:
                    bllFactory.Db.ProjectFields.Where(x => x.Fund == null).Delete();
                    bllFactory.Db.SaveChanges();
                    MessageBox.Show("专项资金信息修改成功！", "专项资金信息修改成功");
                    break;
            }
        }

        private void ButtonDelete_Click(object sender, RoutedEventArgs e)
        {
            if (MessageBox.Show("你确定要删除此资金数据呢？", "确定？", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            {
                bllFactory.Db.Funds.Remove(this.Fund);
                bllFactory.Db.ProjectFields.Where(x => x.Fund == null).Delete();
                bllFactory.Db.SaveChanges();
                MessageBox.Show("专项资金信息删除成功！", "专项资金信息删除成功");
                NavigationCommands.GoToPage.Execute("/Pages/FundQuery.xaml", this);
            }
        }

        private void ButtonAddField_Click(object sender, RoutedEventArgs e)
        {
            if (this.ComboBoxProjectFieldName.SelectedIndex >= 0)
            {
                PromptDialog dialog = new PromptDialog("请输入" + this.ComboBoxProjectFieldName.Text + "的数据：", string.Empty);
                if (dialog.ShowDialog() == true)
                {
                    string value = dialog.Input;
                    this.Fund.ProjectFields.Add(new ProjectField()
                    {
                        FieldName = this.ComboBoxProjectFieldName.Text,
                        FieldValue = value,
                        OrderNo = (this.ComboBoxProjectFieldName.SelectedItem as ProjectField).OrderNo
                    });
                }
            }
            else
            {
                MessageBox.Show("请选择项目信息的名称");
            }
        }

        private void ButtonDeleteField_Click(object sender, RoutedEventArgs e)
        {
            ProjectField projectField = (sender as FrameworkElement).DataContext as ProjectField;
            this.Fund.ProjectFields.Remove(projectField);
        }

        private void ComboBoxFundType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.ComboBoxFundType.SelectedItem != null && this.ComboBoxYear.SelectedItem != null)
            {
                FundType fundType = this.ComboBoxFundType.SelectedItem as FundType;
                int year = (int)this.ComboBoxYear.SelectedItem;
                this.availableProjectFieldNames = bllFactory.ProjectFieldBll.GetProjectFieldNamesForFundType(new DateTime(year, 1, 1), fundType.FundTypeName);
                BindAvailableProjectFieldName(this.availableProjectFieldNames);
            }
        }

        private void BindAvailableProjectFieldName(List<ProjectField> availableFieldName)
        {
            IEnumerable<string> fieldsNeedHide = this.Fund.ProjectFields == null ? new string[]{}: this.Fund.ProjectFields.Select(x => x.FieldName);
            List<ProjectField> comboBoxFields = new List<ProjectField>();
            comboBoxFields.AddRange(this.availableProjectFieldNames);
            comboBoxFields.RemoveAll(x => fieldsNeedHide.Contains(x.FieldName));
            this.ComboBoxProjectFieldName.ItemsSource = comboBoxFields;
            this.ComboBoxProjectFieldName.DisplayMemberPath = "FieldName";
            if (comboBoxFields.Count > 0)
            {
                this.ComboBoxProjectFieldName.SelectedIndex = 0;
            }
        }

        private void ComboBoxYear_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxFundType_SelectionChanged(null, null);
        }
    }
}
